using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace InfoSite.Data
{
	[DataObject]
	[Serializable]
	public partial class SiteUserAccessRole
	{
		#region Constants

		private const string TableName = "[dbo].[SiteUser_AccessRole]";

		#endregion

		#region Properties

		public int? RoleId { get; set; }
		public int? UserId { get; set; }
		public DateTime? CreateDate { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("RoleId", typeof(Int32));
			ds.Tables[TableName].Columns.Add("UserId", typeof(Int32));
			ds.Tables[TableName].Columns.Add("CreateDate", typeof(DateTime));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["RoleId"] = RoleId ?? (object) DBNull.Value;
			dr["UserId"] = UserId ?? (object) DBNull.Value;
			dr["CreateDate"] = CreateDate ?? (object) DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			RoleId = dr["RoleId"] != DBNull.Value ? Convert.ToInt32(dr["RoleId"]) : RoleId = null;
			UserId = dr["UserId"] != DBNull.Value ? Convert.ToInt32(dr["UserId"]) : UserId = null;
			CreateDate = dr["CreateDate"] != DBNull.Value ? Convert.ToDateTime(dr["CreateDate"]) : CreateDate = null;
		}

		public static List<SiteUserAccessRole> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<SiteUserAccessRole> objects = new List<SiteUserAccessRole>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");
			
			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			if (ds.Tables[TableName] == null)
				throw new ApplicationException("Cannot find table [dbo].[SiteUser_AccessRole] in DataSet.");

			if (ds.Tables[TableName].Rows.Count < 1)
				throw new ApplicationException("Table [dbo].[SiteUser_AccessRole] is empty.");

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				SiteUserAccessRole instance = new SiteUserAccessRole();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			return objects;
		}

		#endregion

		#region CRUD Methods

		public static SiteUserAccessRole Get(Int32 roleId, Int32 userId)
		{
			SiteUserAccessRole instance = new SiteUserAccessRole();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspSiteUserAccessRole_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, roleId, userId))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0) throw new ApplicationException(String.Format("Could not get SiteUserAccessRole ID:{0} {1} from Database.", roleId, userId));
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(Int32? roleId, Int32? userId, DateTime? createDate, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspSiteUserAccessRole_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, roleId, userId, createDate))
			{
				if (transaction == null)
					db.ExecuteScalar(dbCommand);
				else
					db.ExecuteScalar(dbCommand, transaction);
			}
		}

		/// <summary>
		/// Insert current SiteUserAccessRole to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(RoleId, UserId, CreateDate, transaction);
		}

		#endregion

		#region UPDATE

		public static void Update(Int32? roleId, Int32? userId, DateTime? createDate, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspSiteUserAccessRole_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@roleId"].Value = roleId;
				dbCommand.Parameters["@userId"].Value = userId;
				dbCommand.Parameters["@createDate"].Value = createDate;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		public static void Update(Int32? roleId, Int32? userId, DateTime? createDate)
		{
			Update(roleId, userId, createDate, null);
		}

		public static void Update(SiteUserAccessRole siteUserAccessRole)
		{
			siteUserAccessRole.Update();
		}

		public static void Update(SiteUserAccessRole siteUserAccessRole, DbTransaction transaction)
		{
			siteUserAccessRole.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		public void Update(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspSiteUserAccessRole_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@roleId"].SourceColumn = "RoleId";
				dbCommand.Parameters["@userId"].SourceColumn = "UserId";
				dbCommand.Parameters["@createDate"].SourceColumn = "CreateDate";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();

					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		public void Update()
		{
			Update((DbTransaction)null);
		}
		#endregion

		#region DELETE

		public static void Delete(Int32? roleId, Int32? userId, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspSiteUserAccessRole_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, roleId, userId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		public static void Delete(Int32? roleId, Int32? userId)
		{
			Delete(roleId, userId, null);
		}

		/// <summary>
		/// Delete current SiteUserAccessRole from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		public void Delete(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspSiteUserAccessRole_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, RoleId, UserId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		/// <summary>
		/// Delete current SiteUserAccessRole from database.
		/// </summary>
		public void Delete()
		{
			Delete(null);
		}

		#endregion

		#region SEARCH

		public static List<SiteUserAccessRole> Search(Int32? roleId, Int32? userId, DateTime? createDate)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspSiteUserAccessRole_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, roleId, userId, createDate))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}

		public static List<SiteUserAccessRole> Search(SiteUserAccessRole searchObject)
		{
			return Search(searchObject.RoleId, searchObject.UserId, searchObject.CreateDate);
		}

		#endregion

		#endregion

		#endregion
	}
}